package com.gmaf.mas.launch.property;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gmaf.mas.launch.FilePathUtils;

public class DefaultConfiguration implements Configuration
{
	private static final Log log = LogFactory.getLog(DefaultConfiguration.class);
	
	private Properties buildInProp = new Properties();
	private Properties localProp = new Properties();
	
	public DefaultConfiguration(URL url)
	{
		initSysProperties(url);
	}

	public DefaultConfiguration()
	{
		this(null);
	}
	
	private void initSysProperties(URL url)
	{
		File file = null;
		do
		{
			if(url == null)
			{
				log.warn("url is null.");
				break;
			}
			
			try
			{
				file = new File(url.toURI());
				file = file.getCanonicalFile();
			}
			catch(URISyntaxException e)
			{
				log.warn("Failed to convert file from url: " + url, e);
			}
			catch(IOException e)
			{
				log.warn("Failed to getCanonicalFile from: " + file, e);
				file = file.getAbsoluteFile();
			}
			
			if(file != null)
			{
				break;
			}
		}
		while(false);
		
		String baseDir = (file != null) ? file.getParent() : ".";
		baseDir = FilePathUtils.getCanonicalPath(baseDir);
		
		buildInProp.put("basedir", baseDir);
	}
	
	public String getProperty(String name)
	{
		String value = null;
		do
		{
			value = localProp.getProperty(name);
			if(value != null)
			{
				break;
			}
			
			value = buildInProp.getProperty(name);
			if(value != null)
			{
				break;
			}
			
			value = System.getProperty(name);
			if(value != null)
			{
				break;
			}
		}
		while(false);

		return value;
	}
	
	public void setProperty(String name, String value)
	{
		localProp.setProperty(name, value);
	}
	
	public Properties getLocalProperties()
	{
		return this.localProp;
	}
	
	public Properties getBuildInProperties()
	{
		return buildInProp;
	}
}
